package vip.xiaonuo.bi.modular.dataset.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.bi.modular.dataset.entity.Dataset;
import vip.xiaonuo.bi.modular.dataset.entity.DatasetFolder;
import vip.xiaonuo.bi.modular.dataset.mapper.DatasetFolderMapper;
import vip.xiaonuo.bi.modular.dataset.service.DatasetFolderService;
import vip.xiaonuo.bi.modular.dataset.service.DatasetService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @auther: 顾育司
 * @Description 数据文件夹
 * @date: 2024/1/12
 */
@Service
public class DatasetFolderServiceImpl extends ServiceImpl<DatasetFolderMapper, DatasetFolder> implements DatasetFolderService {
    @Autowired
    DatasetFolderService datasetFolderService;

    @Autowired
    DatasetService datasetService;

    @Override
    public Object folderlist(String keyWord) {

        // 根据用户获取相对应的分组信息
        List<DatasetFolder> folderlist = datasetFolderService.lambdaQuery().like(ObjectUtils.isNotEmpty(keyWord),DatasetFolder::getName,keyWord ).list();
        List<Dataset> Datasetlist = datasetService.lambdaQuery().like(ObjectUtils.isNotEmpty(keyWord),Dataset::getName,keyWord ).list();

        // 形成树形结构放回
        List<Object> result = new ArrayList<>();
        // 构建id-节点map映射
        Map<String, DatasetFolder> treePidMap = folderlist.stream().collect(Collectors.toMap(DatasetFolder::getId, t -> t));

        // 以组id 数据分组
        for (Dataset dataSet : Datasetlist) {
            if (dataSet.getFolderId()==null) {
                dataSet.setFolderId(0L);
            }
        }

        Map<Long, List<Dataset>> dataMap1 = Datasetlist.stream().collect(Collectors.groupingBy(Dataset::getFolderId));

        // 文件顶级加入
        Datasetlist.stream().filter(item->item.getFolderId()==0).forEach(item->result.add(item));

        // 遍历层级
        folderlist.stream().forEach(node -> {
           if(node.getChildren()==null){
               node.setChildren(new ArrayList<>());
           }
            // 判断根节点
            if (Arrays.asList("0").contains(node.getPid())) {
                result.add(node);
            }
             else {
                //  **** 2插入文件夹*****
                //找到父元素
                DatasetFolder parentNode = treePidMap.get(node.getPid());

                if(parentNode==null){
                    // 可能出现 rootPid 更高的节点 这个操作相当于截断
                    return;
                }
                if (parentNode.getChildren() == null) {
                    parentNode.setChildren(new ArrayList());
                }
                parentNode.getChildren().add(node);
            }
        });

        // 文件夹加入数据集
        folderlist.stream().forEach(node -> {
                        // ****  1插入数据  ****
                // 如果存在数据集即放进去
                if (dataMap1.get(new Long(node.getId()))!=null) {
                    if (node.getChildren()==null) {
                        node.setChildren(new ArrayList<>());
                    }
                    node.getChildren().addAll(dataMap1.get(new Long(node.getId())));
                }

        });

      return   result;
    }

    @Override
    public void careteFolder(String name, String pid) {
        DatasetFolder datasetFolder = new DatasetFolder();
        datasetFolder.setName(name);
        datasetFolder.setPid(pid);
        datasetFolderService.save(datasetFolder);
    }

    @Override
    public void updateByFolderId(String id, String name, String pid) {
        // 文件(数据集)移动
        Dataset byId = datasetService.getById(id);
        if(byId != null){
            Dataset dataset = new Dataset();
            dataset.setId(id);
            if(ObjectUtils.isNotEmpty(name)){
                dataset.setName(name);
            }else {
                dataset.setFolderId(Long.parseLong(pid));
            }
            datasetService.updateById(dataset);
            return;
        }

        // 文件夹移动
        DatasetFolder datasetFolder = new DatasetFolder();
        datasetFolder.setId(id);
        if(ObjectUtils.isNotEmpty(name)){
            datasetFolder.setName(name);
        }else {
            datasetFolder.setPid(pid);
        }
        // 文件(数据集)移动
        datasetFolderService.updateById(datasetFolder);
    }

    @Override
    public void updateBatchByFolderId(String ids, String folderId) {
        List<Dataset> list = new ArrayList<>();
        String[] split = ids.split(",");
        for (int i = 0; i < split.length; i++) {
            Dataset dataset = new Dataset();
            dataset.setId(split[i]);
            dataset.setFolderId(new Long(folderId));
            list.add(dataset);
        }
        datasetService.updateBatchById(list);
    }

    @Override
    public void deleteFolder(String id) {

        // 文件处理
        Dataset byId = datasetService.getById(id);
        if(byId != null){
            datasetService.removeByDataSetId(id);
            return;
        }

        // 文件夹处理
        //1.删除分组
        List<DatasetFolder> list = datasetFolderService.list();
        // 当前组节点包含的那些组
        List<String> result = new ArrayList<>();
        result.add(id);
        // 构建id-节点map映射
        Map<String, DatasetFolder> treePidMap = list.stream().collect(Collectors.toMap(DatasetFolder::getId, t -> t));
        //遍历子节点
        DatasetFolder datasetGroup = treePidMap.get(id);
        getNode(datasetGroup,result,treePidMap);
        //2.删除对应分组与分组下的数据
        //2.1删除组
        datasetFolderService.removeByIds(result);
        // 2.2 删除组里数据
        datasetService.remove(new QueryWrapper<Dataset>()
                .lambda()
                .in(Dataset::getFolderId, result));
    }
    //递归从当前节点 遍历所有相关子节点
    void getNode(DatasetFolder datasetGroups,List<String> result,Map<String, DatasetFolder> treePidMap){
        for (Map.Entry<String, DatasetFolder> map : treePidMap.entrySet()) {
            if (datasetGroups.getId().equals(map.getValue().getPid())) {
                result.add(map.getKey());
                getNode(map.getValue(),result,treePidMap);
            }
        }
        return;
    }
}
